/* $RCSFile: ModuleDefinitionsEdit.aspx.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/AddonNice/PageModules/ModuleDefsAll/ModuleDefinitionsEdit.aspx.cs $
 * $log$
 * Revision 20 2010/08/09 10:51:21  christian.surieux
 *   Added Log comment to all .aspx .ascx .master files
 * Revision 19 2010/08/09 09:43:56  christian.surieux
 *   Added Log to cs sources files
 * Revision 6 2010/08/06 19:56:25  christian.surieux
 *   Added Log to All cs files
 */

using System;
using System.Diagnostics;
using System.Threading;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Globalization;

using AddonNice.UI;
using AddonNice.Settings;
using AddonNice.UI.WebControls;
using AddonNice.Security;
using AddonNice.Configuration;
using AddonNice.Diagnostics;
using AddonNice.Helpers;


using Trace2=   System.Diagnostics.Trace;

namespace AddonNice.PageModules.ModuleDefinitions 
{
	/// <summary>
	/// Add/Remove modules, assign modules to portals
	/// </summary>
	public partial class ModuleDefinitionsEdit : EditItemPage
	{
        ModulesDB modDB	    =   new ModulesDB();
		Guid defID          =   Guid.Empty;

		protected ImageButton selectAllButton;
		protected ImageButton selectNoneButton;

        bool isFileGroupInstal
        {
            get { return (RadTabStrip1.SelectedIndex == 0); }
        }

		/// <summary>
		/// The Page_Load server event handler on this page is used
		/// to populate the role information for the page
		/// </summary>
		private void Page_Load(object sender, System.EventArgs e)
		{
			if (PageTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ModuleDefinitionsEdit Page_Load BEG IsPostBack: {0}",IsPostBack),PageTraceSwitch.Sw.Info);
			// Calculate security defID
			if (Request.Params["defID"] != null) 
				defID			                =   new Guid(Request.Params["defID"]);
            // We Ajaxify some buttons
            AddAjaxSetting(selectAllButton,PortalsName);
            AddAjaxSetting(selectNoneButton,PortalsName);
            // init for progress indicator
            PageProgressArea                    =   RadProgressArea1;
            InitProgress();
            
			// If this is the first visit to the page, bind the definition data 
			if ( !IsPostBack )
			{
                // Pb don't persist netween postbacks InitProgress();
       			if (PageTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ModuleDefinitionsEdit Page_Load defID: {0}",defID),PageTraceSwitch.Sw.Info);

				// Adding modules
                if ( defID == Guid.Empty ) 
				{
					// new module definition
					string strModPath		    =	Config.ModulesPath.Trim(new char[]{'~'});
					InstallerFileName.Text	    =	strModPath+"/MyModuleFolder/install.xml";
					//FriendlyName.Text		    =	"New Definition";
					DesktopSrc.Text			    =	strModPath+"/MyModuleFolder/MyModule.ascx";
				}
				else 
				{
                    RadTabStrip1.SelectedIndex  =   1;
					RadMultiPage1.SelectedIndex =   1;
					// Obtain the module definition to edit from the database
					SqlDataReader dr            =   null;
					try
					{
						dr	                    =	modDB.GetSingleModuleDefinition(defID);
                
						// Read in first row from database
						if ( dr.Read() )
                        {
					        FriendlyName.Text   =   dr[StStr.DBFriendlyName].ToString();
					        DesktopSrc.Text     =   dr[StStr.DBDesktopSrc].ToString();
					        Usage.Text          =   dr[StStr.DBUsage].ToString();
					        lblGUID.Text        =   dr[StStr.DBGeneralModDefID].ToString();
                            Lock.Checked        =   (bool)dr[StStr.DBLock];
                            Admin.Checked       =   (bool)dr[StStr.DBAdmin];
                            CbUpgrade.Checked   =   true; // We propose a module upgrade as a default
					    }
					}
					catch(Exception ex)
					{
						if (PageTraceSwitch.Sw.TraceError)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]ModuleDefinitionsEdit Page_Load GetSingleModuleDefinition ex : {0}",ex),PageTraceSwitch.Sw.Info);
						throw;
					}
					finally
					{
						if ( dr != null )
							dr.Close();
					}
				}

				// Populate checkbox list with all portals
				// and "check" the ones already configured for this tab
				SqlDataReader portalsrd         =   null;
				try
				{
					portalsrd				    =	modDB.GetModuleInUse(defID);

					// Clear existing items in checkboxlist
					PortalsName.Items.Clear();

					while( portalsrd.Read() ) 
					{
                        int pId                 =   (int)portalsrd[StStr.PortalID];
						bool PresentIn          =   ((portalsrd["checked"].ToString()) == "1");
						if ( pId >= 0)
						{
							ListItem item       =   new ListItem();
							item.Text           =   (string) portalsrd[StStr.DBPortalName];
							item.Value          =   pId.ToString();
            
							if (PresentIn ) 
								item.Selected   =   true;
							PortalsName.Items.Add(item);
						}
                        else if ( (pId == StStr.CommonPortalID) && PresentIn ) // common module detected, disable any portal assignment
                        {
                            CbCommonModule.Visible      =   true;
                            CbCommonModule.Enabled      =   false;
                            CbCommonModule.Checked      =   true;
                            PortalsName.Enabled         =   false;
                            foreach(Control ctl in PlaceHolderSelect.Controls)
                                if ( ctl is ImageButton )
                                    ((ImageButton)ctl).Enabled   =   false;
                        }
					}
				}
				catch(Exception ex)
				{
					if (PageTraceSwitch.Sw.TraceError)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]ModuleDefinitionsEdit Page_Load GetModuleInUse ex : {0}",ex),PageTraceSwitch.Sw.Info);
					throw;
				}
				finally
				{
					if ( portalsrd != null )
						portalsrd.Close();
				}
			}
			if (PageTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine("[V]ModuleDefinitionsEdit Page_Load END.",PageTraceSwitch.Sw.Info);
		}

		/// <summary>
		/// Set the module guids with free access to this page
		/// </summary>
		protected override ArrayList AllowedModules
		{
			get
			{
				ArrayList al = new ArrayList();
				al.Add ("D04BB5EA-A792-4E87-BFC7-7D0ED3ADD582");
				return al;
			}
		}

		/// <summary>
		/// OnUpdate installs or refresh module definiton on db
        /// This could be done via a full install proc in xml install file
        /// Or individually for each module
		/// </summary>
        void ModuleDefinitionsEdit_Update(object sender, AddonNice.UI.ADNPageEventArgs e)
		{
			if (PageTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ModuleDefinitionsEdit ModuleDefinitionsEdit_Update BEG DefID: {0}, RadTabStrip1.SelectedIndex: {1}",
                    defID,RadTabStrip1.SelectedIndex),PageTraceSwitch.Sw.Info);
            Hashtable instalTb                  =   new Hashtable();
			try
			{
                installCount                    =   0;
                totalSteps                      =   100;
                bool install                    =   lblGUID.Text == string.Empty;
                StartProgress();

                // Install using the Xml File
                if ( isFileGroupInstal )
                {
                    if ( string.IsNullOrEmpty(InstallerFileName.Text.Trim()) )
                    {
                        LblErrGroupInstall.Text =   LocalizeHelper.Localize("ERROR_ENTER_A_FILE_NAME","You must enter a group install filename");
                        e.Cancel                =   true;
                        return;
                    }
                    string iPath                =   Server.MapPath(AddonNice.Settings.Path.ApplicationRoot + "/" + InstallerFileName.Text);
                    if ( PageTraceSwitch.Sw.TraceVerbose )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ModuleDefinitionsEdit ModuleDefinitionsEdit_Update path: {0}, GUID: [{1}]",iPath,lblGUID.Text),PageTraceSwitch.Sw.Info);
                    ModuleInstall.InstallGroup(instalTb,Wrapper,iPath,install,
                        delegate(string title,int countInc)
                        {
                            installCount        +=  countInc;
                            SetUpdateProgress(title,installCount);
                        });
                }
                // Install using only the module 
                else
                {
                    if ( string.IsNullOrEmpty(FriendlyName.Text.Trim()) )
                    {
                        LblErrFriendlyName.Text     =   LocalizeHelper.Localize("ERROR_ENTER_A_MODULE_NAME","You must enter a module name");
                        e.Cancel                    =   true;
                        return;
                    }
                    if ( string.IsNullOrEmpty(DesktopSrc.Text.Trim()) )
                    {
                        LblErrDesktopSrc.Text       =   LocalizeHelper.Localize("ERROR_INVALID_MODULE","You must enter a valid web path for module");
                        e.Cancel                    =   true;
                        return;
                    }
                    // backucustom and publish if needed 
                    ModuleInstall.Install(instalTb,FriendlyName.Text,DesktopSrc.Text,Usage.Text,install,
                        CbUpgrade.Checked,true,true,
                        delegate(string title,int countInc)
                        {
                            installCount            +=  countInc;
                            SetUpdateProgress(title,installCount);
                        });
                }

				// Update the module definition: when module is not a common module register module for portals
                if ( defID != Guid.Empty )
                {
                    if ( CbCommonModule.Visible && CbCommonModule.Checked )
                        modDB.UpdateModuleDefinitions(defID,StStr.CommonPortalID,true);
                    else for ( int i = 0 ; i < PortalsName.Items.Count ; i++ )
                    {
                        modDB.UpdateModuleDefinitions(defID,Convert.ToInt32(PortalsName.Items[i].Value),(bool)PortalsName.Items[i].Selected);
                    }
                }
                // Flush installTb
                instalTb.Clear();
                // Reset Menu
			    portalSettings.ReloadPortal(true);
                portalSettings.ReloadMenus();
			}
			catch (Exception ex)
			{
				if (PageTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]ModuleDefinitionsEdit ModuleDefinitionsEdit_Update Error updating module ex : {0}", ex),PageTraceSwitch.Sw.Info);
				lblErrorDetail.Text     =   LocalizeHelper.Localize("MODULE_DEFINITIONS_INSTALLING", "An error occurred installing.");
				if (isFileGroupInstal)
					lblErrorDetail.Text +=  " Installer: " + Server.MapPath(AddonNice.Settings.Path.ApplicationRoot + "/" + InstallerFileName.Text);
				else
					lblErrorDetail.Text +=  " Module: '" + FriendlyName.Text + "' - Src: '" + DesktopSrc.Text + "'";
				lblErrorDetail.Visible  =   true;
                e.Cancel                =   true;
                return;
			}
            finally
            {
                EndProgress();
            }
		    if (PageTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ModuleDefinitionsEdit ModuleDefinitionsEdit_Update END DefID: {0}.", defID),PageTraceSwitch.Sw.Info);
		}


		/// <summary>
		/// Delete a Module definition
		/// </summary>
        void  ModuleDefinitionsEdit_Delete(object sender, AddonNice.UI.ADNPageEventArgs e)
		{
			if (PageTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ModuleDefinitionsEdit ModuleDefinitionsEdit_DeleteError BEG isFileGroupInstal: {0}",isFileGroupInstal),PageTraceSwitch.Sw.Info);
            Hashtable instalTb      =   new Hashtable();
			try
			{
                string iPath        =   Server.MapPath(AddonNice.Settings.Path.ApplicationRoot + "/" + InstallerFileName.Text);
				if ( isFileGroupInstal )
					AddonNice.Helpers.ModuleInstall.UninstallGroup(instalTb,
                        Wrapper,iPath,
                        delegate(string title,int countInc)
                        {
                            installCount += countInc;
                            SetUpdateProgress(title,installCount);
                        });
                else
					AddonNice.Helpers.ModuleInstall.Uninstall(instalTb,DesktopSrc.Text,true,true);
			}
			catch(Exception ex)
			{
				if (PageTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]ModuleDefinitionsEdit ModuleDefinitionsEdit_DeleteError deleting module ex : {0}",ex),PageTraceSwitch.Sw.Info);
				lblErrorDetail.Text         =   LocalizeHelper.Localize("MODULE_DEFINITIONS_DELETE_ERROR", "An error occurred deleting module.");
                LblErrDesktopSrc.Text       =  LocalizeHelper.Localize("ERROR_INVALID_MODULE","Invalid module, unable to delete");
                e.Cancel                    =   true;
			}
	        if (PageTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ModuleDefinitionsEdit ModuleDefinitionsEdit_DeleteError END Ok: {0}",!e.Cancel),PageTraceSwitch.Sw.Info);
        }

		/// <summary>
		/// Select all portals for adding the module
		/// </summary>
		void selectAllButton_Click(object sender, ImageClickEventArgs e)
		{
			for (int i = 0; i < PortalsName.Items.Count; i++)
				PortalsName.Items[i].Selected = true;
		}

		/// <summary>
		/// Unselect any selected portal for adding module
		/// </summary>
		void selectNoneButton_Click(object sender, ImageClickEventArgs e)
		{
			for (int i = 0; i < PortalsName.Items.Count; i++)
				PortalsName.Items[i].Selected = false;
		}

		#region Std Overrides
 
        override protected void OnPreInit(EventArgs e)
        {
	        if (PageTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine("[V]ModuleDefinitionsEdit OnPreInit BEG.",PageTraceSwitch.Sw.Info);
            MasterPage m                        =   Master; // to have buttons instanciated, little pb .net
            base.OnPreInit(e);
			string strLoc			            =	Helpers.LocalizeHelper.GetCurrentNeutralCultureName();

		   // Special code to adapt buttons to culture

   			selectAllButton						=	new ImageButton();
			selectAllButton.SkinID				=	"SelectAll_"+strLoc;
			selectAllButton.AlternateText		=	LocalizeHelper.Localize("SELECT_ALL","Select All");
			selectAllButton.CausesValidation	=	false;
			selectAllButton.Enabled				=	true;

		    selectNoneButton					=	new ImageButton();
			selectNoneButton.SkinID				=	"UnSelect_"+strLoc;
			selectNoneButton.AlternateText		=	LocalizeHelper.Localize("SELECT_NONE","Select none");
			selectNoneButton.CausesValidation	=	false;
			selectNoneButton.Enabled			=	true;
	        if (PageTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine("[V]ModuleDefinitionsEdit OnPreInit END.",PageTraceSwitch.Sw.Info);
        }

		override protected void OnInit(EventArgs e)
		{
	        if (PageTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine("[V]ModuleDefinitionsEdit OnInit BEG.",PageTraceSwitch.Sw.Info);
			InitializeComponent();	
			base.OnInit(e);
	        if (PageTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine("[V]ModuleDefinitionsEdit PreInit END.",PageTraceSwitch.Sw.Info);
		}

		private void InitializeComponent() 
		{    
			PlaceHolderSelect.Controls.Add(selectAllButton);
            PlaceHolderSelect.Controls.Add(new LiteralControl("&#160;"));
			PlaceHolderSelect.Controls.Add(selectNoneButton);
						
			selectAllButton.Click		+=	new ImageClickEventHandler(selectAllButton_Click);
			selectNoneButton.Click		+=	new ImageClickEventHandler(selectNoneButton_Click);
			Load						+=	new EventHandler(Page_Load);
            Update                      +=  new PageEventHandler(ModuleDefinitionsEdit_Update);
            Delete                      +=  new PageEventHandler(ModuleDefinitionsEdit_Delete);
 		}


		protected override PlaceHolder placeHolderForButtons
		{
			get
			{ return PlaceHolderButtons; }
			set { }
		}

        protected override PlaceHolder placeHolderForButtons2
		{
			get
			{ return PlaceHolderButtons2; }
			set { }
		}

		#endregion

	}
}